package com.lynn.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lynn.blog.common.ApiResponse;
import com.lynn.blog.common.TokenHolder;
import com.lynn.blog.dto.PostSaveDTO;
import com.lynn.blog.dto.PostUpdateDTO;
import com.lynn.blog.util.JwtUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.lynn.blog.entity.Post;
import com.lynn.blog.mapper.PostMapper;
import com.lynn.blog.service.PostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;

/**
 * 服务层实现。
 *
 * @author root
 * @since 2024-07-15
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Override
    public Boolean savePost(PostSaveDTO dto) {
        Post post = new Post();
        BeanUtil.copyProperties(dto, post);

        post.setCreated(Timestamp.from(Instant.now()));
        post.setLastModified(Timestamp.from(Instant.now()));
        post.setUserId(JwtUtil.getUserIdFromToken(TokenHolder.getToken()));
        return this.save(post);
    }

    @Override
    public ApiResponse<List<Post>> listPosts(Integer uid, Integer pageNum, Integer pageSize, Boolean createdAsc) {
        com.mybatisflex.core.paginate.Page<Post> page = new com.mybatisflex.core.paginate.Page<Post>(pageNum, pageSize);
        QueryWrapper wrapper = new QueryWrapper().where(Post::getUserId).eq(uid).orderBy(Post::getCreated, createdAsc);
        List<Post> records = this.page(page, wrapper).getRecords();
        return ApiResponse.success(records);
    }

    @Override
    public Boolean updateByPostId(Integer id, PostUpdateDTO dto) {
        Long userIdFromToken = JwtUtil.getUserIdFromToken(TokenHolder.getToken());
        QueryWrapper wrapper = new QueryWrapper().where(Post::getUserId).eq(userIdFromToken).where(Post::getPostId).eq(id);
        Post dbData = this.getOne(wrapper);

        if (dbData != null) {
            BeanUtil.copyProperties(dto, dbData);
            dbData.setLastModified(Timestamp.from(Instant.now()));
            return this.updateById(dbData);
        }
        return false;
    }
}
